<?php
namespace App\Extensions\stepbystepchain;

use App\Common\ResponseCode;
use App\Exceptions\BusinessException;
use App\Jobs\ApplylogJob;
use App\Traits\HttpHelper;
use Illuminate\Support\Facades\Log;

/**
 * Created by PhpStorm
 * User: shen.zk
 * Date: 2023/9/7
 * Time: 09:40
 * Comment: ''
 */
class StepByStepChainService
{
    use HttpHelper;

    protected $url;

    protected $proxy=[];

    public static function getInstance(){
        return new self();
    }

    public function __construct()
    {
        $this->url = config('chain.chain_url');
    }

    /**
     * 创建钱包
     * @return mixed
     * @throws BusinessException
     * @author shen.zk
     * @date 2023-09-07 09:52
     */
    public function createWalletAddress()
    {
        return $this->sendRequestPost('/wallet/createWalletAddress');
    }

    /**
     * 发送请求
     * @param string $url
     * @param array $data
     * @return mixed
     * @throws BusinessException
     * @author shen.zk
     * @date 2023-09-07 09:52
     */
    protected function sendRequestPost(string $url,array $data=[])
    {
        $requestUrl = $this->url.$url;

        // 请求发起
        try {
            $response = $this->sendPost($requestUrl, $data, $this->proxy, []);
        } catch (\GuzzleHttp\Exception\GuzzleException $exception) {
            throw new BusinessException(ResponseCode::API_ACCESS_ERROR, ['error' => $exception->getMessage()]);
        }

        $responseStr = $response->getBody()->getContents();
        Log::info("[跬步链]返回数据：{$responseStr}");

        // 异步处理
        $log = [
            'action'=>$requestUrl,
            'apply_info'=>"",
            'result_info'=>$responseStr,
            'create_time'=>date('Y-m-d H:i:s'),
            'type'=>'创建钱包'
        ];

        dispatch(new ApplylogJob($log));

        if (empty($responseStr))
            throw new BusinessException(ResponseCode::API_ACCESS_ERROR, ['error' => '服务异常']);

        $result = json_decode($responseStr, true);

        if (!isset($result['code']) || $result['code'] != 200) {
            Log::info("[跬步链]CODE码不正确");
            throw new BusinessException(ResponseCode::API_ACCESS_ERROR);
        }

        return $result;
    }
}
